package com.icoolkj.learn.juc.future;

import com.icoolkj.learn.juc.base.utils.SleepTools;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/03/05 16:09
 */
@Slf4j
public class CompletableFutureDemo {
    public static void main(String[] args) {
      log.info("kevin 进入餐厅，点了西红柿炒蛋");
        CompletableFuture<String> future = CompletableFuture
                .supplyAsync(() -> {
                    log.info("厨师炒菜");
                    SleepTools.second(2);
                    return "西红柿炒蛋完成";
                })
                .thenCombine(CompletableFuture.supplyAsync(()->{
                    log.info("服务员蒸饭");
                    SleepTools.second(3);
                    return "米饭好了";
                }), (dish, rice) -> {
                    log.info("服务员打饭");
                    SleepTools.second(1);
                    return dish + "，" + rice;
                });
        log.info("kevin 在刷视频");
        log.info("{} , kevin 开吃", future.join());

        log.info("kevin 吃完饭，去结账，要求开发票");
        future = CompletableFuture.supplyAsync(()->{
            log.info("收银员收款");
            SleepTools.second(2);
            return "20";
        }).thenApply(money ->{
            log.info("服务员开发票，面额{}元", money);
            SleepTools.second(3);
            return money +"元发票";
        });
        log.info("kevin 接了个朋友电话");
        log.info("kevin 拿到{}，准备回家。", future.join());

        log.info("kevin 走出餐厅，来到公交站，等待601路或者918路公交车");
        future = CompletableFuture.supplyAsync(()->{
            log.info("601路公交车正在赶来");
            SleepTools.second(3);
            return "601 路公交车到了";
        }).applyToEither(CompletableFuture.supplyAsync(()->{
            log.info("918路公交车正在赶来");
            SleepTools.second(1);
            return "918 路公交车到了";
        }), bus -> {
            if (bus.startsWith("918")) {
                throw new RuntimeException("918 中途车坏了...");
            }
            return bus;
        }).exceptionally(e -> {
            log.info(e.getMessage());
            log.info("kevin 叫了一辆出租车");
            SleepTools.second(3);
            return "出租车到了";
        });
        log.info("{} kevin 坐车回家。", future.join());
    }
}
